/*
 * @# SessionContextHolder.java 2011-12-24 上午10:23:38
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.common;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.ianswer.px.user.entity.UserSession;

/**
 * 用于处理session上下文的数据提取和存储.
 * 
 * @author alvin hwang
 */
public final class SessionContextHolder {

	private SessionContextHolder() {
		// empty!
	}

	/**
	 * 登录用户
	 */
	private static final String CURRENT_USER = "currentUser";

	/**
	 * 获取当前登录的用户标识.
	 * 
	 * @return 当前登录的用户标识.
	 */
	public static Long getUserId() {
		UserSession user = currentUser();
		return user == null ? null : user.getUserId();
	}
	
	/**
	 * 获取当前登录的用户信息.
	 * 
	 * @return 当前登录的用户信息.
	 */
	public static UserSession currentUser() {
		return (UserSession) RequestContextHolder.currentRequestAttributes().getAttribute(CURRENT_USER,
				RequestAttributes.SCOPE_SESSION);
	}

	/**
	 * 存储当前登录的用户信息.
	 * 
	 * @param userSession
	 *            当前登录的用户信息.
	 * @return 当前登录的用户信息.
	 */
	public static UserSession currentUser(UserSession userSession) {
		RequestContextHolder.currentRequestAttributes().setAttribute(CURRENT_USER, userSession,
				RequestAttributes.SCOPE_SESSION);
		return userSession;
	}
}
